<template>
    <base-breadcrumb :title="$route.meta.title">
        <!-- 总包签证报送审批 -->
        <a-form-model
            ref="ruleForm"
            :model="form"
            :label-col="{ span: 6 }"
            :wrapper-col="{ span: 18 }"
            :rules="editModel != 0 ? rules : {}"
        >
            <a-spin :spinning="loading">
                <!-- 表格 -->
                <a-card :bordered="false">
                    <title-name title="基本信息"></title-name>
                    <custom-form
                        :is-emit="false"
                        :formList="formList"
                        :form="form"
                        :editModel="editModel == 0 ? '' : ''"
                         @select="selectOrg"
                         @getProjectInfo="getProjectInfo"
                    >
                        <template v-slot:table>
                            <a-form-model-item label=" " :colon="false">
                                <!-- 表格 -->
                                <s-table
                                    class="mb20"
                                    bordered
                                    ref="table"
                                    tableLayout="fixed"
                                    size="default"
                                    rowKey="id"
                                    :columns="columns"
                                    :data="loadData"
                                    :alert="true"
                                    show-size-changer
                                    show-quick-jumper
                                    :showPagination="false"
                                >
                                    <template
                                        v-for="col in [
                                            'notContainAddedTaxFee',
                                            'addedTaxFee',
                                            'containAddedTaxFee',
                                            'remark'
                                        ]"
                                        :slot="col"
                                        slot-scope="text, record, index"
                                    >
                                        <div :key="col" class="form-item">
                                            <template>
                                                <template v-if="editModel != 0">
                                                    <BaseInput
                                                        v-if="col === 'remark'"
                                                        :class="col === 'remark' ? 'remark' : ''"
                                                        :disabled="editModel == 0"
                                                        v-model="record[col]"
                                                    >
                                                    </BaseInput>
                                                    <span v-else-if="col === 'addedTaxFee'">{{ text }} </span>

                                                    <BaseInputNumber
                                                        v-else
                                                        v-model="record[col]"
                                                        :disabled="editModel == 0"
                                                        :precision="2"
                                                        @change="change(index)"
                                                    >
                                                    </BaseInputNumber>
                                                </template>
                                                <template v-else> {{ text }}</template>
                                            </template>
                                        </div></template
                                    >
                                </s-table>
                            </a-form-model-item>
                        </template>

                        <!-- 附件上传 -->
                        <template #fileList>
                            <template v-if="editModel != 0">
                                <l-table businessCode="BM27" :uploadArrys.sync="form.fileList"></l-table>
                                <!-- <div class="file_prompt">支持扩展名：.rar .zip .doc .docx .pdf .jpg...</div> -->
                            </template>
                            <file-link v-else :fileList="form.fileList" style="margin-top: -3px"></file-link>
                        </template>
                    </custom-form>
                </a-card>
            </a-spin>
            <!-- 页脚操作栏 -->
            <div class="btn_box page-btn-right-top" v-if="editModel != 0">
                <!-- <a-button class="button_right" v-if="id != '' && form.auditStatus == 'DRAFT'" type="danger" @click="handleRemove()"
                    >删除草稿</a-button
                > -->
                <a-button
                    class="button_right"
                    v-if="form.status == 'REJECTED'"
                    type="primary"
                    :loading="loading.REJECTED"
                    @click="handleSubmit('REJECTED')"
                    >保存</a-button
                >
                <a-button
                    v-else
                    class="button_right"
                    type="primary"
                    :loading="loading.DRAFT"
                    @click="handleSubmit('DRAFT')"
                    >保存草稿</a-button
                >
                <a-button
                    class="button_right"
                    type="primary"
                    :loading="loading.SUBMITTED"
                    @click="handleSubmit('SUBMITTED')"
                    >提交</a-button
                >
                <a-button type="primary" @click="handleActiveClose">关闭</a-button>
            </div>
            <div class="btn_box page-btn-right-top" v-else>
                <a-button type="primary" @click="handleActiveClose">关闭</a-button>
            </div>
        </a-form-model>
         <selectApprover :businessId="businessId"  :processConfig="setProcessConfig"></selectApprover>
    </base-breadcrumb>
</template>

<script>
import { getMeasureList, addMeasure, getMeasure } from '@/api/businessAffairs/lumpSumMeasurement'
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import SelectProject from '@/components/Select/SelectProject' // 分公司
import moment from 'moment'
import SelectPersonByProject from '@/components/Select/SelectPersonByProject' // 分公司
import { types, status } from './model'
import {
    getCommercialViasSendApproveById,
    addCommercialVisaSendApprove,
    updateCommercialVisaSendApprove
} from '@/api/businessAffairs/lumpSumMeasurement'
const columns = [
    {
        title: '项目/金额',
        dataIndex: 'projectFeeStr'
    },
    {
        title: '1.不含增值税（元）',
        dataIndex: 'notContainAddedTaxFee',
        scopedSlots: { customRender: 'notContainAddedTaxFee' }
    },
    {
        title: '2.增值税（元）',
        dataIndex: 'containAddedTaxFee',
        scopedSlots: { customRender: 'containAddedTaxFee' }
    },
    {
        title: '含增值税（元）（1+2）',
        dataIndex: 'addedTaxFee',
        scopedSlots: { customRender: 'addedTaxFee' }
    },
    {
        title: '备注',
        dataIndex: 'remark',
        scopedSlots: { customRender: 'remark' }
    }
]
export default {
    name: 'a' + Date.now(),
    extends: new BaseEditPage(),
    components: {
        SelectPersonByProject
    },
    data() {
        this.columns = columns
        return {
            loading: false, // 加载控件
            visible: false, //人员选择控件
            editModel: 0, // 操作状态:0 查看;1 编辑;2 新增
            form: {
                projectDeptId: '',
                projectId:null,
                floorRateOfProfit: '',
                measureDetailDefine: [
                    {
                        addedTaxFee: null,
                        remark: null,
                        containAddedTaxFee: null,
                        notContainAddedTaxFee: null,
                        projectFeeStr: '报送金额'
                    },
                    {
                        addedTaxFee: null,
                        remark: null,
                        containAddedTaxFee: null,
                        notContainAddedTaxFee: null,
                        projectFeeStr: '保底值'
                    },
                    {
                        addedTaxFee: null,
                        remark: null,
                        containAddedTaxFee: null,
                        notContainAddedTaxFee: null,
                        projectFeeStr: '对应成本'
                    }
                ]
            }, // 表单
            id: '',
            loadData: () => {
                if (this.form.measureDetailDefine.length > 0) {
                    return new Promise((resolve, reject) => {
                        resolve({
                            data: this.form.measureDetailDefine
                        })
                    })
                }
            },
            loadingBtn: {
                DELETE: false,
                DRAFT: false,
                SUBMITTED: false,
                REJECTED: false
            },
            rules: {
                visaName: [{ required: true, message: '请输入' }],
                typleId: [{ required: true, message: '请选择' }],
                visaId: [{ required: true, message: '请输入' }],
                contractValuationBasis: [{ required: true, message: '请输入' }],
                saveFileDept: [{ required: true, message: '请输入' }],
                submitTime: [{ required: true, message: '请选择' }],
                contractAppointSubmitTime: [{ required: true, message: '请选择' }],
                daysInvolvedInConstructionPeriodChange: [{ required: true, message: '请选择' }],
                chargePeopleList: [{ required: true, message: '请选择' }],
                visaClaimDescriptionAndCalculationProcess: [{ required: true, message: '请输入' }]
            }, // 校验规则
            init: false, // 初始化控件

            disabledDateList: [],
            //获取流程配置值
            processConfig: null,
            //点击提交发送流程配置值
            setProcessConfig: null,
            businessId: null
        }
    },
    props: {
        isAudit: {
            // 是否作为审批详情
            type: Boolean,
            default: false
        }
    },
    watch: {
        isAudit: {
            immediate: true,
            handler(val) {
                if (val) {
                    this.$nextTick(() => {
                        this.editModel = 0
                    })
                }
            }
        }
    },
   async mounted() {
        this.$route.meta.title = ['总包签证报送审批 查看', '总包签证报送审批 编辑', '总包签证报送审批 新增'][
            this.editModel
        ]

        // 不为添加时请求详情
        if (this.editModel != 2) {
            this.loading = true
            getCommercialViasSendApproveById({ id: this.id })
                .then((res) => {
                    this.loading = false
                    console.log(res)
                    this.form = { ...this.form, ...res.data }
                    console.log(this.form)

                    this.$nextTick(() => {
                        this.init = true
                        this.$refs.table.refresh(true)
                    })
                })
                .catch(() => {
                    this.loading = false
                })
        } else {
            this.form.projectId = this.$userInfo().currentPost.projectId;
            this.$nextTick(() => {
                this.init = true
            })
        }
          //获取通过获取流程配置值
    this.processConfig = await this.$getConfigFn('commercial_visa_send_approve');
    },
    computed: {
        formList() {
            return [
                {
                    label: '所属单位',
                    type: 'orgTree',
                    keyName: 'projectId',
                    rules: [{ required: true, message: '请选择项目名称', trigger: 'change' }],
                    span: 16,
                    isAutoSelectFirst: true,
                    isNeedAuth:true ,
                    checkStrictly: true,
                    disabled: true,
                    viewName: "viewName",
                },
                // {
                //     type: SelectSubCompany,
                //     keyName: 'branchComId',
                //     label: '分公司名称',
                //     disabled: true,
                //     attrs: {
                //         isDefaultSelected: this.editModel == 2,
                //         autoSelected: this.editModel == 2
                //     }
                // },
                // {
                //     type: SelectProject,
                //     keyName: 'projectId',
                //     label: '项目名称',
                //     disabled: true,
                //     attrs: {
                //         isDefaultSelected: this.editModel == 2,
                //         autoSelected: this.editModel == 2,
                //         keyValue: 'branchComId',
                //         isClear: this.editModel == 2,
                //         isEdit: this.editModel != 2,
                //         form: this.form
                //     },
                //     selectChange: (e) => {
                //         this.$set(this.form, 'projectDeptId', e.projectDeptId)
                //     }
                // },
                {
                    type: 'BaseInput',
                    label: '签证名称',
                    disabled: this.editModel == 0,
                    keyName: 'visaName'
                },
                {
                    keyName: 'typleId',
                    type: 'a-select',
                    label: '类型',
                    disabled: this.editModel == 0,
                    data: types
                },
                {
                    type: 'BaseInput',
                    label: '签证编号',
                    disabled: this.editModel == 0,
                    keyName: 'visaId'
                },
                {
                    type: 'BaseInput',
                    label: '合同计价依据',
                    disabled: this.editModel == 0,
                    keyName: 'contractValuationBasis'
                },
                {
                    type: 'BaseInput',
                    label: '存档部门',
                    disabled: this.editModel == 0,
                    keyName: 'saveFileDept'
                },
                {
                    keyName: 'submitTime',
                    type: 'a-date-picker',
                    disabled: this.editModel == 0,
                    label: '报送时间',
                    attrs: {
                        valueFormat: 'YYYY-MM-DD'
                    }
                },
                {
                    keyName: 'contractAppointSubmitTime',
                    type: 'a-date-picker',
                    disabled: this.editModel == 0,
                    label: '合同约定应报送时间',
                    attrs: {
                        valueFormat: 'YYYY-MM-DD'
                    }
                },

                {
                    slot: true,
                    customItemSlot: true,
                    keyName: 'table',
                    span: 24
                },
                {
                    type: 'BaseInputNumber',
                    label: '保底利润率%',
                    disabled: true,
                    keyName: 'floorRateOfProfit'
                },
                {
                    type: 'BaseInputNumber',
                    label: '涉及工期变更天数',
                    disabled: this.editModel == 0,
                    keyName: 'daysInvolvedInConstructionPeriodChange',
                    wrap: true,
                    attrs: {
                        min: 0,
                        isInt: true
                    }
                },

                {
                    keyName: 'chargePeopleList',
                    type: SelectPersonByProject,
                    disabled: this.editModel == 0,
                    label: '责任人',
                    attrs: {
                        isOrg: true,
                        showSearch: true,
                        orgId: this.form.projectDeptId,
                        mode: 'multiple'
                    }
                },
                {
                    keyName: 'visaClaimDescriptionAndCalculationProcess',
                    type: 'BaseTextarea',
                    label: '签证索赔描述及计算过程',
                    disabled: this.editModel == 0,
                    attrs: {
                        maxLength: 3000
                    },
                    span: 24
                },
                {
                    keyName: 'fileInfoList',
                    type: 'uploadFile',
                    label: '附件上传',
                    disabled: this.editModel == 0,
                    span: 24,
                    businessCode: 'FACE07'
                }
            ]
        }
    },
    methods: {
        //选择单位
        selectOrg(val) {
            if (val && val.length) {
                this.form.branchComId = val[val.length - 2].orgId
            }
        },
        //获取项目详情
        getProjectInfo(e) {
            this.$set(this.form, 'projectDeptId', e.projectDeptOrgId)
        },
        /**
         * 输入框事件
         */
        change(index) {
            console.log(this.form.measureDetailDefine[index])

            this.form.measureDetailDefine[index].addedTaxFee = parseFloat(
                this.form.measureDetailDefine[index].containAddedTaxFee +
                    this.form.measureDetailDefine[index].notContainAddedTaxFee
            ).toFixed(2)

            this.$refs.table.refresh(true)

            if (index != 0) {
                if (this.form.measureDetailDefine[1].addedTaxFee == 0) {
                    this.form.floorRateOfProfit = 0
                } else {
                    this.form.floorRateOfProfit = (
                        ((this.form.measureDetailDefine[1].addedTaxFee - this.form.measureDetailDefine[2].addedTaxFee) /
                            this.form.measureDetailDefine[1].addedTaxFee) *
                        100
                    ).toFixed(2)
                    this.form.floorRateOfProfit = this.form.floorRateOfProfit == 'NaN' ? 0 : this.form.floorRateOfProfit
                }
            }
        },

        validateTable(list) {
            let flag = true

            list.forEach((item) => {
                if (item.notContainAddedTaxFee == null || item.containAddedTaxFee == null) {
                    flag = false
                }
            })
            if (!flag) {
                this.$message.warning('请完善表格后提交')
            }
            return flag
        },
        validateForm() {
            let flag = false
            let flag1 = false
            flag1 = this.validateTable(this.form.measureDetailDefine)
            this.$refs.ruleForm.validate((e) => {
                if (e) {
                    flag = true
                }
            })
            if (flag && flag1) {
                return true
            } else {
                return false
            }
        },
        /**
         * 提交表单
         */
        async handleSubmit(status) {
           this.setProcessConfig = null;
            if (status == 'SUBMITTED') {
                // 校验表单
                if (!this.validateForm()) {
                    return
                }
            }

            this.loading = true
            this.loadingBtn[status] = true
            let form = this.$clone(this.form)

            if (status != 'REJECTED') {
                form.auditStatus = status == 'SUBMITTED' ? 1 : 0
            } else {
                form.auditStatus = 5
            }
            let api = [updateCommercialVisaSendApprove, addCommercialVisaSendApprove][this.editModel - 1] // 根据操作切换url地址
            this.submitApprovalConfirm(status =='SUBMITTED'?this.processConfig:6, (flag)=>{
              if(!flag) {
                this.loading = false
                this.loadingBtn[status] = false
                return
              }
            api(form)
                .then((res) => {
                    this.loading = false
                    this.loadingBtn[status] = false
                    this.$message.success(status == 'SUBMITTED' ? '提交成功！' : '保存成功')
                    //提交时，返回id
                    if(status =='SUBMITTED') {
                        //提交时，返回id
                            this.businessId = res.data?.id || this.id;
                            this.setProcessConfig = this.processConfig;
                            return
                        }else{
                        this.$multiTab.close()
                    }
                })
                .catch(() => {
                    this.loadingBtn[status] = false
                    this.loading = false
                    this.$message.warning(err.data.message)
                })
            })
        }
    }
}
</script>
<style lang="less" scoped>
/deep/ .form-item  {
    .ant-input:not([disabled]),
    .ant-select:not(.ant-select-disabled) .ant-select-selection,
    .ant-calendar-picker-input,
    .ant-input-number:not([disabled]),
    .ant-cascader-picker {
        border-color: #e4ac0b;
        background-color: #fff9e8;
    }
    .remark {
        .ant-input {
            border-color: inherit;
            background-color: initial;
        }
    }
}
</style>
